package xyz.whiteblue.core;

import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import java.io.File;

/**
 * Created by WhiteBlue on 15/6/2.
 */
public class Config {
    public static ServletContext SERVLET_CONTEXT;
    private static String CONTENT_PATH;
    private static String CLASS_ROOT_PATH;
    private static String ENCODE;

    private static String TEMPLATE_PATH = "/WEB-INF/views";//模板文件路径

    private static Class CONFIG_CLASS;//额外的配置类

    private static boolean DEV_MODE = false;//开发模式


    private static Config config = new Config();

    private Config() {
    }

    public static Config getConfig() {
        return config;
    }

    public void init(ServletContext servletContext, FilterConfig filterConfig) {
        SERVLET_CONTEXT = servletContext;
        this.initPath();
        ENCODE = filterConfig.getInitParameter("encoding");
        this.initTemplate(filterConfig.getInitParameter("template"));
    }


    /**
     * 模板路径
     *
     * @param templatePath 模板路径
     */
    private void initTemplate(String templatePath) {
        if (templatePath != null) {
            TEMPLATE_PATH = templatePath;
            if (TEMPLATE_PATH.endsWith("/"))
                TEMPLATE_PATH = TEMPLATE_PATH.substring(0, TEMPLATE_PATH.length() - 1);
        }
    }


    /**
     * 初始化路径
     */
    private void initPath() {
        if (CLASS_ROOT_PATH == null) {
            try {
                String e = Config.class.getClassLoader().getResource("").toURI().getPath();
                CLASS_ROOT_PATH = (new File(e)).getAbsolutePath();
            } catch (Exception var2) {
                String path = Config.class.getClassLoader().getResource("").getPath();
                CLASS_ROOT_PATH = (new File(path)).getAbsolutePath();
            }
        }

        if (CONTENT_PATH == null) {
            CONTENT_PATH = SERVLET_CONTEXT.getContextPath();
        }

    }

    public static ServletContext getServletContext() {
        return SERVLET_CONTEXT;
    }

    public static String getTemplatePath() {
        return TEMPLATE_PATH;
    }


    public static String getClassRootPath() {
        return CLASS_ROOT_PATH;
    }

    public static String getContentPath() {
        return CONTENT_PATH;
    }

    public static String getENCODE() {
        return ENCODE;
    }

    public static Class getConfigClass() {
        return CONFIG_CLASS;
    }

    public static void setConfigClass(Class configClass) {
        CONFIG_CLASS = configClass;
    }

    public static boolean isDevMode() {
        return DEV_MODE;
    }

    public static void setDevMode(boolean devMode) {
        DEV_MODE = devMode;
    }

}
